#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: demo_pydantic.py 
@version:
@time: 2022/01/17 
"""
# Pydantic 数据校验功能
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: Optional[datetime] = None
    friends: List[int] = []


external_data = {
    'id': '123',
    'signup_ts': '2019-06-01 12:22:23',
    'friends': [1, 2, '3'],
}

user = User(**external_data)
print(user.id)
print(type(user.id))
# > 123
# > <class 'int'>
print(repr(user.signup_ts))
# > datetime.datetime(2019, 6, 1, 12, 22)
print(user.friends)
# > [1, 2, 3]
print(user.dict())
"""
{
    'id': 123,
    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
    'friends': [1, 2, 3],
    'name': 'John Doe',
}
"""

print(user.schema_json(indent=2))

m = User.parse_raw('{"id": 123, "name": "James"}')
print(m)